# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.ext import db
from google.appengine.api import memcache

KEY_NAME_PREFIX = 'TAG_'

class YTTag(db.Model):
    category = db.StringProperty(multiline=False)
    ref = db.ReferenceProperty(collection_name='yttag_ref_set') 
    ext = db.ReferenceProperty(collection_name='yttag_ext_set') 
  
    name = db.StringProperty(required=True, multiline=False)
    number = db.IntegerProperty(default=0)
    sort = db.IntegerProperty(default=0)
    date = db.DateTimeProperty(auto_now=True)
  
    @classmethod
    def get_or_insert_by_name(cls, tag_name, **kwds):
        try:      
            return YTTag.get_or_insert(KEY_NAME_PREFIX+tag_name, **kwds)
        except:
            return None  

    @classmethod
    def get_by_name(cls, tag_name):
        return YTTag.get_by_key_name(KEY_NAME_PREFIX+tag_name)

    @classmethod
    def add_tags(cls, tags):
        try:
            for tag in tags:
                tag_info = YTTag.get_or_insert_by_name(tag, name=tag)
                tag_info.number = tag_info.number + 1
                tag_info.put()
        except:
            pass

    @classmethod
    def remove_tags(cls, tags):
        try:
            for tag in tags:
                tag_info = YTTag.get_by_name(tag)
                if tag_info and tag_info.number > 0: 
                    tag_info.number = tag_info.number - 1
                    tag_info.put()
        except:
            pass

    def get_parent(self):
        return None
